﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.DataModel;
using YArchitech.LIB;
using YArchitech.Revit;
using YRevitJig;

namespace YArchitech.Plumbing
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class DrawLineAndWriteLength : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			UIApplication application = commandData.Application;
            Autodesk.Revit.ApplicationServices.Application application2 = application.Application;
			Document document = application.ActiveUIDocument.Document;
			UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
			if (!YJKRevitTools.ViewCheck(activeUIDocument, new List<ViewType>
			{
				(ViewType)1,
				(ViewType)2,
				(ViewType)115
			}))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			if (DrawLineAndWriteLength.hWndRevit == null)
			{
				DrawLineAndWriteLength.hWndRevit = new YJKWindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			FormAllLineLength formAllLineLength = new FormAllLineLength();
			ElementSet elementSet = new ElementSet();
			UserSetting userSetting = new UserSetting();
			bool flag = Convert.ToBoolean(userSetting.GetValue("AllLineLength", "DeleteDls"));
			formAllLineLength.Show(DrawLineAndWriteLength.hWndRevit);
			int wMsg = 7;
			DrawLineAndWriteLength.SendMessage(DrawLineAndWriteLength.hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			formAllLineLength.textBox1.Text = "0.0";
			formAllLineLength.textBox2.Text = "0.0";
			formAllLineLength.checkBox1.Checked = flag;
			transaction = new Transaction(document, "绘制折线");
			transaction.Start();
			Selection selection = activeUIDocument.Selection;
			Result result;
			try
			{
				XYZ xyz = selection.PickPoint("请选择绘制线段的起点：");
				XYZ xyz2 = new XYZ(xyz.X, xyz.Y, xyz.Z);
				double num = 0.0;
				double num2 = 0.0;
				int num3 = 0;
				Line line = null;
				Line line2 = null;
				List<XYZ> list = new List<XYZ>();
				list.Add(xyz);
				using (XLineJig xlineJig = new XLineJig(activeUIDocument))
				{
					for (;;)
					{
						try
						{
							if (formAllLineLength.Visible)
							{
								ViewAssist.ViewValidating(activeUIDocument.Document, activeUIDocument.ActiveView);
								xlineJig.StartPoint = xyz;
								XYZ xyz3 = xlineJig.PickEndPoint(xyz, "请选择绘制线段的下一点：");
								if (xyz.IsAlmostEqualTo(xyz3))
								{
									MessageBox.Show("不能选择两个重合的点！", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
								}
								else
								{
									list.Add(xyz3);
									DetailLine detailLine = YJKRevitTools.DrawDetailLine(document, xyz, xyz3);
									elementSet.Insert(detailLine);
									num3++;
									num += Math.Round((detailLine.Location as LocationCurve).Curve.Length * 0.3048, 3);
									if (num3 % 2 == 0)
									{
										line2 = ((detailLine.Location as LocationCurve).Curve as Line);
									}
									else if (num3 % 2 == 1)
									{
										line = ((detailLine.Location as LocationCurve).Curve as Line);
									}
									if (num3 >= 2 && line2 != null && line != null)
									{
										Math.Round(line.Length * 0.3048, 3);
										Math.Round(line2.Length * 0.3048, 3);
										line.Direction.AngleTo(line2.Direction);
										num2 = Math.Round(YJKRevitTools.CalArea(list) * 0.3048 * 0.3048, 3);
										formAllLineLength.textBox2.Text = num2.ToString();
									}
									xyz = xyz3;
									formAllLineLength.textBox1.Text = num.ToString();
									if (!xyz2.IsAlmostEqualTo(xyz3))
									{
										continue;
									}
									XYZ origin = selection.PickPoint("请选择标注面积和周长的点");
									document.GetTextNode(document.ActiveView, origin, XYZ.BasisX, XYZ.BasisY, 0.24384000000000003, (Autodesk.Revit.DB.TextAlignFlags)64, string.Concat(new object[]
									{
										"周长：",
										num.ToString(),
										" m\n面积：",
										num2,
										" m^2"
									}));
								}
							}
						}
						catch
						{
						}
						break;
					}
				}
				flag = formAllLineLength.checkBox1.Checked;
				userSetting.WriteValue("AllLineLength", "DeleteDls", flag.ToString());
				this.DeleteDatailLines(flag, elementSet, application);
				formAllLineLength.Close();
				document.Regenerate();
				transaction.Commit();
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				flag = formAllLineLength.checkBox1.Checked;
				formAllLineLength.Close();
				this.DeleteDatailLines(flag, elementSet, application);
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception)
			{
				formAllLineLength.Close();
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
                if (transaction != null && (int)transaction.GetStatus() != 3)
				{
					formAllLineLength.Close();
					transaction.RollBack();
				}
			}
			return result;
		}

		private bool DeleteDatailLines(bool bDelete, ElementSet detailLines, UIApplication uiApp)
		{
			if (!bDelete)
			{
				return false;
			}
			if (detailLines.Size < 1)
			{
				return false;
			}
			IEnumerator enumerator = detailLines.GetEnumerator();
			bool flag = enumerator.MoveNext();
			while (flag)
			{
				Element element = enumerator.Current as Element;
				uiApp.ActiveUIDocument.Document.Delete(element.Id);
				flag = enumerator.MoveNext();
			}
			return true;
		}

		public static YJKWindowHandle hWndRevit;
	}
}
